package com.xunmall.base.validation.validator;


import com.xunmall.base.util.StringUtils;
import com.xunmall.base.validation.annotation.IsNumeric;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: WangYanjing
 * @Date: 2018/12/27 10:53
 * @Description:
 */
public class IsNumericValidator implements ConstraintValidator<IsNumeric, String> {

    private Map<String, String[]> patterns;

    private String type;

    private String locale;

    @Override
    public void initialize(IsNumeric constraintAnnotation) {
        this.patterns = new HashMap<String, String[]>();
        this.patterns.put("zh_CN", new String[]{"^\\+?[1-9][0-9]*$"});
        this.type = constraintAnnotation.type();
        this.locale = constraintAnnotation.locale();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StringUtils.isEmpty(value)) {
            return true;
        }
        if (!patterns.containsKey(locale)) {
            return true;
        }
        return StringUtils.match(value, patterns.get(locale)[0]);
    }

}
